package co.salehi.web;

import javax.servlet.http.HttpServletRequest;

import co.salehi.domain.Cart;
import co.salehi.domain.LabourCharge;
import org.springframework.roo.addon.web.mvc.controller.RooWebScaffold;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@RooWebScaffold(path = "labourcharges", formBackingObject = LabourCharge.class)
@RequestMapping("/labourcharges")
@Controller
public class LabourChargeController {

	@RequestMapping(params = { "addToCart", "selectedItems" }, method = RequestMethod.GET)
	public String addToCart(Model uiModel, HttpServletRequest request) {

		String str = request.getParameter("selectedItems");

		Cart sessionCart = request.getSession().getAttribute("cart") == null ? new Cart()
				: (Cart) request.getSession().getAttribute("cart");

		for (String idStr : str.split(",")) {
			sessionCart.getLabourChargeIds().add(Long.parseLong(idStr));
		}

		request.getSession().setAttribute("cart", sessionCart);

		return "labourcharges/list";
	}

	@RequestMapping(value = "/{id}", params = "form", method = RequestMethod.GET)
	public String updateForm(@PathVariable("id") Long id, Model uiModel) {
		uiModel.addAttribute("labourCharge", LabourCharge.findLabourCharge(id));
		return "labourcharges/update";
	}

	@PreAuthorize("hasAuthority('ROLE_ADMIN')")
	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	public String delete(@PathVariable("id") Long id,
			@RequestParam(value = "page", required = false) Integer page,
			@RequestParam(value = "size", required = false) Integer size,
			Model uiModel) {
		LabourCharge.findLabourCharge(id).remove();
		uiModel.asMap().clear();
		uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
		uiModel.addAttribute("size", (size == null) ? "10" : size.toString());
		return "redirect:/labourcharges";
	}
}
